﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Ooaavee.Data.Model;

namespace Ooaavee.Data.Queries
{
    [CollectionDataContract]
    public sealed class QueryResultRowValueCollection : Collection<QueryResultRowValue>
    {
        private readonly object _lock = new object();

        [DataMember]
        private Dictionary<Column, QueryResultRowValue> _values;

        public QueryResultRowValue this[Column column]
        {
            get
            {
                if (column == null)
                {
                    throw new ArgumentNullException("column");
                }

                lock (_lock)
                {
                    if (_values == null)
                    {
                        _values = new Dictionary<Column, QueryResultRowValue>();
                    }
                    return _values[column];
                }
            }
        }

        public new void Add(QueryResultRowValue item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            if (item.Column == null)
            {
                throw new ArgumentException("Column is missing.", "item");
            }

            base.Add(item);

            lock ( _lock)
            {
                if (_values == null)
                {
                    _values = new Dictionary<Column, QueryResultRowValue>();
                }
                _values.Add(item.Column, item);                
            }
        }
    }
}
